<!-- equipmentLedger -->
<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" :class="isCloseTree ? 'tag-nav-close' : ''">
        <div class="main-content">
          <div class="form-box">
            <BasicForm @register="registerForm">
              <template #slotBtns class="page-form-slotbtn">
                <div class="btn-box">
                  <a-button class="btn-box-item" @click="throttleReset" style="margin-right: 10px"
                    >重置</a-button
                  >
                  <a-button class="btn-box-item" type="primary" @click="throttleSubmit"
                    >查询</a-button
                  >
                </div>
              </template>
            </BasicForm>
          </div>
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :clickToRowSelect="false"
            :showIndexColumn="true"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="hasPermission(['3-1-update', '3-1-del']) ? actionColumn : undefined"
            rowKey="code"
          >
            <template #bodyCell="{ column, record }">
              <!-- 报警状态开启红色，应答绿色，关闭灰色 -->
              <template v-if="column.key === 'AlarmStatus_text'">
                <span
                  :class="
                    record[column.key] === '开启'
                      ? 'red'
                      : record[column.key] === '应答'
                      ? 'green'
                      : 'gray'
                  "
                >
                  {{ record[column.key] }}
                </span>
              </template>
              <template v-if="column.key === 'AlarmLevel_text'">
                <span :style="{ color: `${levelColorObj[record[column.key]]}` }">
                  {{ record[column.key] }}
                </span>
              </template>
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: '应答告警',
                      ifShow: hasPermission('7-1-2-respondAlarm'),
                      icon: 'ant-design:alert-outlined',
                      onClick: handleSet.bind(null, record),
                    },
                    {
                      label: '远程诊断',
                      ifShow: hasPermission('7-1-2-respondAlarm'),
                      icon: 'ant-design:setting-outlined',
                      onClick: openRouter.bind(null, record),
                    },
                  ]"
                />
              </template>
            </template>
            <!-- <template #toolbar>
              <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
                <a-button class="btn-box-item" type="primary" @click="throttleSubmit"
                  >查询</a-button
                >
            </template> -->
          </BasicTable>
          <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
              :show-total="(total) => `共 ${total} 条数据`"
              showSizeChanger
              size="small"
              :current="paginationInfo.data.current"
              :pageSize="paginationInfo.data.pageSize"
              :total="paginationInfo.data.total"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { PageWrapper } from '/@/components/Page';
  // eslint-disable-next-line
  import { ref, onMounted, reactive, h, unref, nextTick } from 'vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { Pagination } from 'ant-design-vue';
  import { getdevicetypes } from '/@/api/equipmentType/index';
  import { getdevicemodels, getdatalist } from '/@/api/equipmentModel/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getalarmrecord, changealarmstatus } from '/@/api/alertRules/index';
  import { setObjectLocalStorage } from '/@/storage/storage';
  import dayjs from 'dayjs';
  import { useGo } from '/@/hooks/web/usePage';

  const go = useGo();
  const APagination = Pagination;
  let loading = ref(false);
  let tableData = reactive([]);
  // 设备类型
  let deviceTypeList = [];
  // 设备型号
  let deviceModelList = [];
  // 设备类别
  let CategoryObj = [];
  //使用状态
  let statusList = [];
  let isCloseTree = ref(false);

  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  const { hasPermission } = usePermission();
  const { createConfirm, createMessage } = useMessage();
  //报警级别颜色
  const levelColorObj = {
    提示: '#3399CC',
    轻微: '#33CCCC',
    一般: '#FFCC00',
    严重: '#FF9999',
    紧急: '#993399',
  };

  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'AssetCode',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 6,
      },
    },

    {
      field: 'ModelCode',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
      },
    },

    {
      field: 'TypeCode',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
      },
    },
    {
      field: 'AlarmLevelCode',
      component: 'Select',
      label: '报警级别',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
    },
    {
      field: 'AlarmStatusCode',
      component: 'Select',
      label: '报警状态',
      colProps: {
        span: 6,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
    },
    {
      field: 'btns',
      component: 'Input',
      label: '',
      slot: 'slotBtns',
      colProps: {
        span: 4,
      },
    },
  ];
  const [registerForm, { validateFields, setFieldsValue, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { t } = useI18n();
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });

  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '报警编码',
      dataIndex: 'AlarmCode',
      width: 150,
    },
    {
      title: '设备编码',
      dataIndex: 'AssetCode',
      width: 200,
    },
    {
      title: '设备名称',
      dataIndex: 'DeviceName',
      width: 300,
    },
    {
      title: '设备型号编码',
      dataIndex: 'ModelCode',
      width: 250,
    },
    {
      title: '设备型号名称',
      dataIndex: 'ModelName',
      width: 250,
    },
    {
      title: '设备类型',
      dataIndex: 'TypeName',
      width: 300,
    },
    // {
    //   title: '告警名称',
    //   dataIndex: 'AlarmFullName',
    //   width: 300,
    // },
    {
      title: '报警级别',
      dataIndex: 'AlarmLevel_text',
    },
    {
      title: '报警主题',
      dataIndex: 'AlarmTopic',
    },
    {
      title: '报警类型',
      dataIndex: 'AlarmType',
    },
    // {
    //   title: '变量',
    //   dataIndex: 'TagFullName',
    //   width: 300,
    // },
    {
      title: '报警状态',
      dataIndex: 'AlarmStatus_text',
    },
    {
      title: '报警值',
      dataIndex: 'AlarmValue',
    },
    // {
    //   title: '限值',
    //   dataIndex: 'LimitValue',
    // },
    {
      title: '报警时间',
      dataIndex: 'TriggerTime',
    },
    {
      title: '关闭值',
      dataIndex: 'RecoveryValue',
    },
    {
      title: '关闭时间',
      dataIndex: 'RecoveryTime',
    },
    {
      title: '应答时间',
      dataIndex: 'ResponseTime',
    },
    {
      title: '描述',
      dataIndex: 'Description',
    },
  ];
  // 操作栏
  let actionColumn = {
    width: 200,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };

  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  // 获取设备类型
  async function getDeviceTypes() {
    try {
      loading.value = true;

      let res = await getdevicetypes([
        {
          PageNO: 1,
          PageSize: 500,
        },
      ]);
      deviceTypeList = res.Rows;
      updateSchema({
        field: 'TypeCode',
        componentProps: {
          options: deviceTypeList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //获取报警级别
  async function getAlarmLevel() {
    try {
      loading.value = true;

      let res = await getdatalist([
        {
          Code: 'AlarmLevel',
        },
      ]);

      CategoryObj = res;
      updateSchema({
        field: 'AlarmLevelCode',
        componentProps: {
          options: CategoryObj,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  //获取报警状态
  async function getStatus() {
    try {
      loading.value = true;

      let res = await getdatalist([
        {
          Code: 'alarmstatus',
        },
      ]);

      statusList = res;
      updateSchema({
        field: 'AlarmStatusCode',
        componentProps: {
          options: statusList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  // 获取设备型号
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          PageSize: 50,
        },
      ]);
      deviceModelList = res.Rows;

      updateSchema({
        field: 'ModelCode',
        componentProps: {
          options: deviceModelList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 重置按钮点击事件
  async function handleResetFields() {
    initSearch();
    getTableData();
  }
  // 重置搜索条件
  function initSearch() {
    setFieldsValue({
      TypeCode: '',
      SearchModelCode: '',
      SearchCategory: '',
      Manufacturer: '',
      SearchDeviceName: '',
      UseStatsCode: '',
      SearchCode: '',
    });
    paginationInfo.data.current = 1;
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    try {
      let res = await validateFields();
      getTableData(res);
    } catch {}
  }

  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  function handleSet(_record) {
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '温馨提示'),
      content: () => h('span', `是否确认触发应答告警（${_record.AlarmFullName}）`),
      onOk: async () => {
        try {
          await changealarmstatus([_record]);
          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
        } catch (error) {}
      },
    });
  }
  //远程诊断
  function openRouter(_record) {
    setObjectLocalStorage('localDataByAlarmrecord', { _record });
    go('/alarmManagement/diagnosis');
  }

  // 获取设备集合
  async function getTableData(params = {}) {
    clearSelectedRowKeys();
    try {
      loading.value = true;
      let res = await getalarmrecord([
        {
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      // tableData = res.Rows;
      let levelObj = {
        0: '信息',
        1: '次要',
        2: '一般',
        3: '主要',
        4: '严重',
      };
      let AlarmStatusObj = {
        0: '无',
        1: '告警',
        2: '响应',
        3: '恢复',
      };
      tableData = res.Items.map((item) => {
        item.TriggerTime =
          item.TriggerTime && dayjs(item.TriggerTime).format('YYYY-MM-DD HH:mm:ss');
        item.RecoveryTime =
          item.RecoveryTime && dayjs(item.RecoveryTime).format('YYYY-MM-DD HH:mm:ss');
        item.ResponseTime =
          item.ResponseTime && dayjs(item.ResponseTime).format('YYYY-MM-DD HH:mm:ss');

        item.AlarmLevelCn = levelObj[item.AlarmLevel];
        item.AlarmStatusCn = AlarmStatusObj[item.AlarmStatus];

        return item;
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  onMounted(async () => {
    getTableData();
    getDeviceTypes();
    getDeviceModels();
    getAlarmLevel();
    getStatus();
  });
</script>
<script lang="ts">
  export default {
    name: 'EquipmentLedgerIndexPage',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .search-box {
        display: flex;
        align-items: center;

        > .ant-btn-sm {
          height: 32px;
        }
      }

      .main-nav {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        width: 240px;
        height: calc(100%);
        padding: 8px;
        box-sizing: border-box;
        overflow: auto;
        border-right: 1px solid #ccc;

        ::v-deep(.vben-tree__title) {
          user-select: none !important;
        }
      }

      .main-sidebar {
        position: absolute;
        top: 0;
        left: 240px;
        bottom: 0;
        width: 12px;
        border-radius: 5px;
        cursor: pointer;
        user-select: none;

        .close-btn {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12px;
          height: 30px;
          margin-top: -50%;

          line-height: 30px;
          text-align: center;
          background: #7dcdfe;
          border-radius: 6px;
          color: #fff;

          > span {
            font-size: 12px !important;
          }
        }
      }

      .main-sidebar:hover {
        background-color: #e2e3e5;
      }

      .main-content {
        position: relative;
        height: 100%;
        //margin-left: 260px;
        overflow: hidden;

        .pagination-box {
          z-index: 9;
          padding: 10px 5px;
          box-sizing: border-box;
          position: absolute;
          width: 100%;
          bottom: 0;
          left: 0;
          right: 0;
          background-color: #fff;
        }
      }

      .main-content::after {
        content: '';
        display: block;
        width: 100%;
        height: 45px;
      }
    }

    .tag-nav-close {
      .main-nav {
        left: -260px;
      }

      .main-sidebar {
        left: 0;
      }

      .main-content {
        margin-left: 20px;
      }
    }
  }

  .form-box {
    padding: 5px;

    ::v-deep(.ant-form-item) {
      margin: 0 5px;
      margin-bottom: 8px;
    }
  }

  .red {
    color: red;
  }

  .green {
    color: green;
  }

  .gray {
    color: gray;
  }
</style>
